package distributed.controller;

import java.sql.Date;

import org.w3c.dom.NamedNodeMap;

import distributed.entity.Event;
import distributed.entity.EventModel;

import server.ClientState;
import xml.Message;

/**
 * Controller to handle an admin requesting information about events
 * @author Sam Jaffe
 *
 */
public class RequestReportController implements IProtocolController{

	/** Processes a message from a client */
	public Message process(ClientState state, Message request) {
		String xmlString;
		//Get the request attributes
		NamedNodeMap map = request.contents.getFirstChild().getAttributes();
		String key = map.getNamedItem("key").getNodeValue(); //Get the session key
		if (!key.equals(state.getData())) { // Validate
			xmlString = Message.responseHeader(request.id(), "Invalid Authentication Key")
					+ "<reportResponse/></response>";
			return new Message(xmlString); // If its bad, throw us out
		}
			
		
		boolean open = map.getNamedItem("type").getNodeValue().equals("open");
		//Are we looking at open or closed events?
		xmlString = Message.responseHeader(request.id()) + "<reportResponse>";
		
		EventModel em = EventModel.getInstance();
		Event event;
		for (String id : em.getEventIDs()) {
			event = em.getEvent(id);
			if (event.done() != open) // Shenanigans
				xmlString += "<entry id='" + id + "' type='" + (event.isOpen() ? "open" : "closed") +
						"' question=\"" + event.getQuestion() + "\" numChoices='" + event.getCount() + 
						"' numRounds='" + event.getRounds() + "' created='" +
						event.getCreationDate() + "' completed='" + event.done() + "'/>";
		}
		
		DataBaseController dbc = DataBaseController.getInstance();
		try {
			for (String id : dbc.getIdsOfOldEvents(new Date(System.currentTimeMillis()+86400000L))) {
				event = dbc.retrieveEvent(id);
				if (event.done() != open)
					xmlString += "<entry id='" + id + "' type='" + (event.isOpen() ? "open" : "closed")
					+ "' question=\"" + event.getQuestion() + "\" numChoices='" +
							event.getCount() + "' numRounds='" + event.getRounds() + "' created='" +
							event.getCreationDate() + "' completed='" + event.done() + "'/>";
			}
		} catch (Exception e) {}
		
		xmlString += "</reportResponse></response>";
		//Let us know all that data
		return new Message(xmlString);
	}
	
	/**
	 * @return RequestReportController
	 */
	public IProtocolController newCopy() {
		return new RequestReportController();
	}

}
